/*
Written by Best Flash Solutions, Inc  
See:
	http://www.bestflashsolutions.com
Contact me: contact@bestflashsolutions.com
*/

/**
 * Load XML file
 */
package com.bestflashsolutions.app
{
	import com.bestflashsolutions.app.Message;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	//
	//Load XML
	//
	public class XMLLoader extends EventDispatcher
	{
		public var objData: XML;
		public var strError: Message=null;


		private var urlLoader:URLLoader;
		
		public function XMLLoader()
		{
			
		}
		
		//Request to server with GIVEN params in POST
		public function load(strUrl:String, objParams:URLVariables=null):void {
			try {
				var objDataRequest:URLRequest = new URLRequest(strUrl);
				if (objParams) {
					//Using POST method
					objDataRequest.method = URLRequestMethod.POST;				
					objDataRequest.data = objParams;
				}
				urlLoader = new URLLoader();
				urlLoader.addEventListener(Event.COMPLETE, onXMLLoadedHandler);
				urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onXMLErrorHandler);
				urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onXMLErrorHandler);
				//Start sent to PHP Server script
				urlLoader.load(objDataRequest);
			}
			catch (event:Error) {
				strError = Message.ERR_WEBSERVER_UNKNOWN;
				objData = null;
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		 
		//Receive data from server
		protected function onXMLLoadedHandler(evt:Event):void {
			urlLoader.removeEventListener(Event.COMPLETE, onXMLLoadedHandler);
			var dataLoader:URLLoader = evt.target as URLLoader;
			strError = null;
			try { 
				//cast --> XML
				objData = new XML(dataLoader.data);
			}
			catch (e: Error) {
				strError = new Message(Message.ERROR, e.toString());
				objData = null;
			}
			//Notify COMPLETE
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		//Error request
		protected function onXMLErrorHandler(evt:Event):void {
			/*
			if (evt is SecurityErrorEvent)
				strError = new Message(Message.ERROR, (evt as SecurityErrorEvent).text);
			else if (evt is IOErrorEvent)
				strError = new Message(Message.ERROR, (evt as IOErrorEvent).text);
			else
				strError = new Message(Message.ERROR, "Unknown error happen");
			*/
			strError = Message.ERR_WEBSERVER_UNKNOWN;
			objData = null;
			dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}